package com.dpj.seckill.rabbitmq;

import com.dpj.seckill.pojo.GoodsVo;
import com.dpj.seckill.pojo.SeckillMessage;
import com.dpj.seckill.pojo.SeckillOrder;
import com.dpj.seckill.pojo.TUser;
import com.dpj.seckill.service.GoodsService;
import com.dpj.seckill.service.OrderService;
import com.dpj.seckill.utils.JsonUtil;
import com.dpj.seckill.vo.RespBean;
import com.dpj.seckill.vo.RespBeanEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiver {
//
//    @RabbitListener(queues = "queue")
//    public void receive(Object msg){
//            log.info("接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_fanout01")
//    public void receive01(Object msg){
//        log.info("Queue01接收消息"+msg);
//    }
//
//    @RabbitListener(queues = "queue_fanout02")
//    public void receive02(Object msg){
//        log.info("Queue02接收消息"+msg);
//    }
//
//
//    @RabbitListener(queues = "queue_direct01")
//    public void receive03(Object msg){
//        log.info("Queue01接受消息"+msg);
//    }
//    @RabbitListener(queues = "queue_direct02")
//    public void receive04(Object msg){
//        log.info("Queue02接受消息"+msg);
//    }
//
//
//    @RabbitListener(queues = "queue_topic01")
//    public void receive05(Object msg){
//        log.info("Queue01接收消息"+msg);
//    }
//    @RabbitListener(queues = "queue_topic03")
//    public void receive06(Object msg){
//        log.info("Queue02接收消息"+msg);
//    }

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderService orderService;

    //下单操作
    @RabbitListener(queues = "seckillQueue")
    public void receive(String message){
        log.info("接受的消息"+message);
        SeckillMessage seckillMessage = JsonUtil.jsonStr2Object(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        TUser user = seckillMessage.getUser();
        GoodsVo goodVo = goodsService.findGoodsVoByGoodsId(goodId);
        if(goodVo.getStockCount()<1){
            return;
        }

        //判断是否重复购买
        SeckillOrder seckillOrder=(SeckillOrder) redisTemplate.opsForValue().get("order"+user.getId()+":"+goodId);
        if(seckillOrder!=null){
            return ;
        }
        //下单操作
        orderService.seckill(user,goodVo);



    }
}
